import React, { Component } from "react";
import LinearGradient from 'react-native-linear-gradient';
import { StyleSheet, findNodeHandle, UIManager, View } from 'react-native';
import Slider from '@react-native-community/slider';

class ChargeIndicator extends Component {
  
  constructor(props) {
    super(props);
    this.state = {
      style:{
        width:'0%'
      },
      width:0
    }
    this.gradient = null;
  }

  componentDidMount() {
    this.measureSize()
  }

  measureSize() {
    let handler = findNodeHandle(this.gradient);
    setTimeout(() => {
      UIManager.measure(handler, (x, y, width, height, pageX, pageY) => {
        this.setState({ width });
      })
    });
  }

  render() {
    return (
      <>
        <LinearGradient ref={(ref) => { 
          this.gradient = ref; 
        }}
        onLayout={(e)=>{
          let {width} = e.nativeEvent.layout;
          this.setState({ width });
        }}
          start={{ x: 0, y: 0.5 }} end={{ x: 1, y: 0.5 }}
          colors={['#006DAC', '#42B95F']}
          style={[styles.linearGradient, this.state.style]}>
          {
            ((width) => {
              let els = [];
              const lineW = 2;
              const gap = 3;
              const lineC = (width - gap) / (lineW + gap)
              // console.log(`width = ${width}, count = ${lineC}`);
              for (let i = 0; i < lineC; i++) {
                // const left = gap + i * (gap + lineW)
                const el = <View key={`${i}`} style={[styles.verLine,{marginLeft:gap}]}></View>
                els.push(el)
              }
              return els;
            })(this.state.width)
          }
        </LinearGradient>
        <Slider
          onValueChange={(value)=>{
            this.setState({
              style:{
                width:`${value*80}%`
              }
            })
            // this.measureSize()
          }}
          style={styles.slider}
          minimumValue={0}
          maximumValue={1}
          minimumTrackTintColor="skyblue"
          maximumTrackTintColor="#000000"
        />
      </>
    )
  }
}

var styles = StyleSheet.create({
  verLine:{
    width:2,
    height:'100%',
    backgroundColor:'skyblue',
    position:'relative',
    opacity:0.8
  },
  line1:{
    width:2,
    height:'100%',
    backgroundColor:'skyblue',
    position:'relative',
    left:10,
    opacity:0.8
  },
  linearGradient: {
    marginTop:50,
    width: '80%',
    marginLeft: '10%',
    borderRadius: 1,
    height: 10,
    flexDirection: 'row'
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'Gill Sans',
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
  slider: {
    width: '80%',
    marginLeft: '10%',
    height: 40,
    marginTop: 40
  }
});

export default ChargeIndicator;